package com.limh.readers.activity

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Intent
import android.os.Handler
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import butterknife.BindView
import butterknife.OnClick
import com.limh.readers.R
import com.limh.readers.bean.Magazine
import com.limh.readers.widget.recyclerview.adapter.CommonAdapter
import com.limh.readers.widget.recyclerview.adapter.MultiItemTypeAdapter
import com.limh.readers.widget.recyclerview.base.ViewHolder
import com.limh.readers.widget.recyclerview.decoration.SpacesItemDecoration
import com.limh.readers.comm.Comm
import com.limh.readers.net.BaseRetrofit
import com.limh.readers.net.ServerApi
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.LogUtil
import com.limh.readers.utils.SharePreferUtils
import com.limh.readers.utils.Utils
import rx.schedulers.Schedulers

/**
 * Function:
 * author: limh
 * time:2017/7/27
 */
class ArtListActivity : BaseActivity() {

    @BindView(R.id.txt_period)
    lateinit var txtPeriod: TextView
    @BindView(R.id.recycle_list)
    lateinit var recycleList: RecyclerView
    @BindView(R.id.refresh_art)
    lateinit var refresh: SwipeRefreshLayout

    lateinit var dialog: ProgressDialog;

    private lateinit var name: String   //期刊名称
    private lateinit var period: String //期数
    private lateinit var artList: MutableList<Magazine>
    private lateinit var adapter: CommonAdapter<Magazine>
    private val bgId = intArrayOf(R.drawable.bg_1, R.drawable.bg_2, R.drawable.bg_3, R.drawable.bg_4,
            R.drawable.bg_5, R.drawable.bg_6, R.drawable.bg_7, R.drawable.bg_8)

    val TAG = "ArtListActivity"

    override fun findView() {
        setContentView(R.layout.activity_artlist)
        dialog = ProgressDialog(this)
        dialog.setMessage("正在加载，请稍后...")
    }

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        name = intent.getStringExtra("name")
        period = intent.getStringExtra("period")
        txtPeriod.text = name + "：" + period

        recycleList.layoutManager = LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false)
        recycleList.addItemDecoration(SpacesItemDecoration(Utils.dip2px(this,
                10f), Utils.dip2px(this, 10f)))

        refresh.setBackgroundResource(bgId[getRadom()])
        refresh.setOnRefreshListener {
            getArtList()
        }
        refresh.isRefreshing = true
    }

    override fun initDatas() {
        if ("" == SharePreferUtils.get(this, name + period, ""))
            getArtList()
        else {
            LogUtil.d(TAG, "章节已缓存")
            artList = GsonUtils.str2List(SharePreferUtils.get(this, name + period,
                    "") as String, Magazine::class.java)
            handler.sendEmptyMessage(0x123)
        }
    }

    @OnClick(R.id.image_close)
    fun OnClick(view: View) {
        when (view.id) {
            R.id.image_close -> finish()
        }
    }

    fun getArtList() {
        val params = mapOf(Pair("name", name), Pair("period", period), Pair("token", Comm.TOKEN))
        LogUtil.w(TAG, "本期参数：" + params.toString())
        val service = BaseRetrofit().createService(ServerApi::class.java)
        service.getMagazine(params)
                .subscribeOn(Schedulers.newThread())
                .subscribeOn(Schedulers.io())
                .subscribe({ response ->
                    when (response.getCode()) {
                        200 -> {
                            artList = GsonUtils.str2List(GsonUtils.Gson2Str(response.getData()), Magazine::class.java)
                            SharePreferUtils.put(this, name + period, GsonUtils.list2Str(artList))
                            sendMsg("", 0x123, handler)
                        }
                        else -> sendMsg(response.getMessage(), 0x124, handler)
                    }
                }, { t ->
                    LogUtil.w(TAG, "异常：" + t.toString())
                    sendMsg("请求失败", 0x124, handler)
                }, {})
    }

    /**
     * 获取0-7之间的随机数
     */
    fun getRadom(): Int {
        var radomNum = SharePreferUtils.get(this, "bg", 0) as Int
        radomNum += 1
        if (radomNum >= 7)
            radomNum = 0
        SharePreferUtils.put(this, "bg", radomNum)
        return radomNum
    }

    private val handler = Handler(Handler.Callback { msg ->
        val b = msg.data
        when (msg.what) {
            0x123 -> {
                for (item in artList)
                    LogUtil.w(TAG, "data=" + item.toString())

                adapter = object : CommonAdapter<Magazine>(this, R.layout.view_item_magazine_list, artList) {
                    override fun convert(holder: ViewHolder, t: Magazine, position: Int) {
                        holder.setText(R.id.txt_item_title, t.artTitle!!)
                        holder.setText(R.id.txt_item_author, t.artAuthor!!)
                    }
                }
                adapter.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener {
                    override fun onItemClick(view: View, holder: RecyclerView.ViewHolder, position: Int) {
                        val intent: Intent = Intent(this@ArtListActivity, WebInfoActivity::class.java)
                        intent.putExtra("title", artList[position].artTitle)
                        intent.putExtra("artLink", artList[position].artUrl)
                        intent.putExtra("id",artList[position].id)
                        intent.putExtra("table", "magazine")
                        intent.putExtra("author", artList[position].artAuthor)

                        startActivity(intent)
                    }
                })
                recycleList.adapter = adapter
            }
            else -> showToastShort(b.getString("msg"))
        }
        if (refresh.isRefreshing) refresh.isRefreshing = false
        if (dialog.isShowing) dialog.dismiss()
        true
    })
}